package cn.kkcxy.blog.system.factory.wechat.impl;

import cn.kkcxy.blog.common.utils.RedisUtil;
import cn.kkcxy.blog.core.enums.WeChatMessageTypeEnum;
import cn.kkcxy.blog.system.factory.wechat.WechatMessageHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReceiveTextMessageHandler implements WechatMessageHandler {

    private static final String KEY_WORD = "验证码";

    public static final String KEY_RRE = "weblog.auth.wechat";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WeChatMessageTypeEnum getMessageType() {
        return WeChatMessageTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收到用户发送文本消息");

        String content = msgMap.get("Content");
        if (!KEY_WORD.equals(content)) {
            return "";
        }

        String toUserName = msgMap.get("ToUserName");
        String fromUserName = msgMap.get("FromUserName");
        Random random = new Random();
        int num = 0;
        String buildKey = KEY_RRE + ":";
        // 判断验证码是否已包含
        do {
            num = random.nextInt(8999) + 1000;
            buildKey = buildKey + num;
        } while (redisUtil.exist(buildKey));

        redisUtil.setNx(buildKey, fromUserName, 3L, TimeUnit.MINUTES);

        String numContent = "您当前的验证码是:" + num + "，三分钟内有效";
        String msg = "<xml><ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "<CreateTime>" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")) + "</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return msg;
    }
}
